<?php

namespace app\base\command;


use app\base\model\RedianData;
use app\base\model\RedianTask;
use app\base\service\TaskService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
/**
 * 定时任务执行处理
 * Class SmsNum
 * @package app\common\command
 */
class CrontabTaskRun extends Command
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xbase:crontabTaskRun');
        $this->setDescription('CrontabTaskRun');
    }

    protected function execute(Input $input, Output $output)
    {
        $user_ids =$this->app->db->name("ai_user")->whereTime("expire_date",'>',date("Y-m-d H:i:s"))->column('id');

        $tasks = RedianTask::mQuery()
            ->where(['status'=>1,'is_deleted'=>0])->whereIn('type','1,4')
            ->whereIn('user_id',$user_ids)
//            ->where(function ($query) {
//                $query->where('count', '<', 'total_count');
//            })
            ->select()->toArray();
      //  $output->info(json_encode($tasks));
        foreach ($tasks as $task){
            if($this->shouldRun($task)){
                $task_run_log_id = $this->app->db->name("task_run_log")->insertGetId([
                    'task_id'=>$task['id'],
                    'num'=>$task['count']+1,
                    'user_id'=>$task['user_id'],
                    'title'=>$task['title'],
                ]);
//                if($task['push_schedule'] && $task['is_auto_fb']==1){
//                    $schedule = json_decode($task['push_schedule'],true);
//                    foreach ($schedule as $v){
//                        $run_script = [];
//                        if($task['is_auto_jjjb']==1){
//                            $run_script[]=$this->app->db->name("script_confg")->where('type',0)->value('id');
//                        }
//                        if($task['is_auto_fbjb']==1){
//                            $run_script[]=$this->app->db->name("script_confg")->where('type',$v['platform'])->value('id');
//                        }
//                        if($v['schedule_type']==2){
//                            foreach ($v['target_device'] as $v2){
//                                $save_schedule = [
//                                    'schedule_value'=>1,
//                                    'schedule_type'=>$v['schedule_type'],
//                                    'push_num'=>1,
//                                    'target_device'=>$v2,
//                                    'task_id'=>$task['id'],
//                                    'user_id'=>$task['user_id'],
//                                    'platform'=>$v['platform'],
//                                    'status'=>0,
//                                    'is_auto_jjjb'=>$task['is_auto_jjjb'],
//                                    'is_auto_fbjb'=>$task['is_auto_fbjb'],
//                                    'run_script'=>json_encode($run_script)
//                                ];
//                                $this->app->db->name('redian_push_schedule')->insert($save_schedule);
//                            }
//                        }else{
//                            foreach ($v['target_device'] as $v2){
//                                foreach ($v['schedule_time'] as $v3){
//                                    $save_schedule = [
//                                        'schedule_value'=>implode(',',$v3['time']),
//                                        'schedule_type'=>$v['schedule_type'],
//                                        'push_num'=>$v3['push_num'],
//                                        'target_device'=>$v2,
//                                        'task_id'=>$task['id'],
//                                        'user_id'=>$task['user_id'],
//                                        'platform'=>$v['platform'],
//                                        'status'=>0,
//                                        'is_auto_jjjb'=>$task['is_auto_jjjb'],
//                                        'is_auto_fbjb'=>$task['is_auto_fbjb'],
//                                        'run_script'=>json_encode($run_script)
//                                    ];
//                                    $this->app->db->name('redian_push_schedule')->insert($save_schedule);
//                                }
//                            }
//                        }
//                    }
//                }
                RedianTask::mQuery()->where([ "id"=>$task['id']])->inc('count')
                    ->update([
                        'error_status'=>0,
                        'progress'=>0,
                        'status'=>3,
                        'last_push'=>date('Y-m-d H:i:s')
                    ]);
                if($task['type']==1){
                    $code = sysqueue($task['title']."热点转换任务", "xbase:TaskRunV2", $later = 1, $data = [
                        'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id
                    ], $rscript = 1, $loops = 0);
                }else{
                    $code = sysqueue($task['title']."对标账号转换任务", "xbase:TaskRunAccount", $later = 1, $data = [
                        'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id
                    ], $rscript = 1, $loops = 0);
                }


                $output->info("任务【{$task['title']}】{$task['id']}开始执行_{$code}");
            }

        }
        $this->setQueueSuccess("任务完成");


    }

    // 判断是否需要执行
    private function shouldRun($task)
    {
        if($task['type']==1){
            if($task['is_auto_fb']==1){
                $schedule_task = json_decode($task['schedule_task'],true);
                $current = time();
                $last_push = strtotime($task['last_push']);
                foreach ($schedule_task as $v){
                    $star_time = strtotime(date("Y-m-d"). $v[0]);
                    $end_time = strtotime(date("Y-m-d"). $v[1]);
                    if(($current>$star_time && $current<$end_time) && ($last_push<$star_time || $last_push>$end_time)){
                        return true;
                    }
                }
                return false;
            }else{
                if($task['last_push']){
                    $last_push = date("Y-m-d",  strtotime($task['last_push']));
                    if($last_push==date("Y-m-d")){
                        return false;
                    }else{
                        return true;
                    }
                }else{
                    return true;
                }

            }
        }else{
            return $this->accountTask($task);
        }

    }

    //对标账号任务是否运行判断
    protected function accountTask($task)
    {
        if($task['schedule_type']==1){
            $schedule_task = json_decode($task['schedule_task'],true);
            $current = time();
            $last_push = strtotime($task['last_push']);
            foreach ($schedule_task as $v){
                $star_time = strtotime(date("Y-m-d"). $v[0]);
                $end_time = strtotime(date("Y-m-d"). $v[1]);
                if(($current>$star_time && $current<$end_time) && ($last_push<$star_time || $last_push>$end_time)){
                    return true;
                }
            }
            return false;
        }else{
            $current = time();
            $last_push = strtotime($task['last_push']);
            $schedule_value = $task['schedule_value'];
            if($current-($last_push+($schedule_value*60))>0){
                return true;
            }else{
                return false;
            }
        }

    }



}
